package coreMiddleware

import (
	"strings"

	"github.com/gin-gonic/gin"
)

func SchemeDetector() gin.HandlerFunc {
	return func(c *gin.Context) {
		scheme := ""

		// 1. 优先用 Nginx/反向代理传的 X-Forwarded-Proto
		if forwardedProto := c.Request.Header.Get("X-Forwarded-Proto"); forwardedProto != "" {
			scheme = strings.ToLower(forwardedProto)
		}

		// 2. 如果没有，从 TLS 判断
		if scheme == "" {
			if c.Request.TLS != nil {
				scheme = "https"
			} else {
				scheme = "http"
			}
		}

		// 存到 context
		c.Set("scheme", scheme)

		// 继续处理
		c.Next()
	}
}
